using System;

namespace SharpMud.LPC
{
    public class Integer : LPC.Object
	{
		private int _Value;
		
		public Integer()
			:this(0)
		{
		}

		public Integer(int value)
		{
			_Value = value;
		}

		public int Value
		{
			get
			{
				return _Value;
			}
			set
			{
				_Value = value;
			}
		}

		public override string ToParsableString()
		{
			return Value.ToString();
		}

        public static explicit operator String(Integer val)
        {
            if (val.Value == 0)
                return new String(0);
            else
                throw new InvalidCastException("You cannot convert a non-zero Integer to an String.");
        }

        public static implicit operator int(Integer val)
        {
            return val.Value;
        }

        public static implicit operator Integer(int val)
        {
            return new Integer(val);
        }

        protected override Object Clone()
        {
            return new Integer(this._Value);
        }

        #region Static Stuff
        public static bool TryParse(char[] text, ref int index, out LPC.Object result)
        {
            char cc = text[index];
            int i2 = index, sign = 1;

            result = null;
            if (!(Char.IsLetterOrDigit(cc) || cc == '+' || cc == '-'))
                return false;
            
            if (cc == '-') { sign = -1; i2++; }
            else if (cc == '+') { sign = 1; i2++; }
            char cc2 = text[i2];
            string numberText = "";

            for (; (i2 < text.Length && Char.IsLetterOrDigit(cc2)); i2++, cc2 = text[i2])
            { numberText += cc2; }
            if (sign < 0)
                numberText = "-" + numberText;
            int number;
            bool sp = int.TryParse(numberText, out number);

            if (sp)
                result = new LPC.Integer(number);
            else
                throw new InvalidLpcFormatException();

            index = i2+1;
            return sp;
        }

        //public static LPC.Integer Parse(char[] textCharacters, ref int index)
        //{
        //    char cc = textCharacters[index];
        //    int i2=index, sign=1;
            

        //    if      (cc == '-')  {   sign = -1;  i2++; }
        //    else if (cc == '+')  {   sign =  1;  i2++; }
        //    char cc2 = textCharacters[i2];
        //    string numberText = "";

        //    for (i2=i2;     (i2<textCharacters.Length && Char.IsLetterOrDigit(cc2));    i2=i2+1,cc2=textCharacters[i2])
        //    {   numberText += cc2; }
        //    if (sign < 0)
        //        numberText = "-" + numberText;
        //    int number;
        //    bool sp = int.TryParse(numberText, number);
        //    index = i2;
        //    if (sp)
        //        return new LPC.Integer(number);
        //    else
        //        return null;
        //}
        #endregion
    }
}
